#include "Precompiled.hpp"

const float ServiceManager::fixedSecondsPerFrame = 0.016f;

ServiceManager::ServiceManager() : remainingTime(0.0f)
{
  QueryPerformanceFrequency(&performanceFrequency);
}

ServiceManager::~ServiceManager()
{}

void ServiceManager::AddService(ServiceInterface* newService)
{
  myServices.push_back(newService);
}

void ServiceManager::Run()
{
  QueryPerformanceCounter(&previousTime);
  //need to change once messaging is in
  while(true)
  {
    Update();
  }
}

void ServiceManager::InitializeAll()
{
  for (unsigned int index = 0; index < myServices.size(); ++index)
  {
    myServices[index]->Initialize();
  }
}

void ServiceManager::Update()
{
  QueryPerformanceCounter(&currentTime);
  remainingTime += static_cast<float>(currentTime.QuadPart - previousTime.QuadPart)/performanceFrequency.QuadPart;
  if(remainingTime < fixedSecondsPerFrame)
  {
    FrameUpdate();
  }
  else
  {
    while(remainingTime >= fixedSecondsPerFrame)
    {
      FrameUpdate();
      TimeUpdate(fixedSecondsPerFrame);
      remainingTime -= fixedSecondsPerFrame;
    }
  }
}
void ServiceManager::FrameUpdate()
{
  for (unsigned int index = 0; index < myServices.size(); ++index)
  {
    myServices[index]->FrameUpdate();
  }
}

void ServiceManager::TimeUpdate(float secondsPassed)
{
  for (unsigned int index = 0; index < myServices.size(); ++index)
  {
    myServices[index]->TimeUpdate(secondsPassed);
  }
}